﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Models.ICModels;
using Casamiel.API.Application.Models.Mall.Req;
using Casamiel.API.Application.Models.Mall.Rsp;
using Casamiel.API.Application.Models.Store;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Exceptions;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.IC;
using Casamiel.Domain.Response.MWeb;

using Enyim.Caching;

using MediatR;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 全国配商城接口
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [ApiController]
    [EnableCors("any")]
    [Authorize]
    public class MallController : BaseController
    {
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("MallService");
        private readonly IMallService _mallService;
        private readonly IMemberCardService _memberCardService;
        private readonly IIcApiService _icApiService;
        private readonly INetICService _netICService;
        private readonly MallSettings _mallSettings;
        private readonly ICasaMielSession _session;
        private readonly IPaymentService _paymentService;
        private readonly IPayGateWayService _gateways;
        private readonly IWxService _wxLogin;
        private readonly IRefundService _refundService;
        private readonly IUserLogService _userLogService;
        private readonly IOrderService _order;
        private readonly IMediator _mediator;
        private readonly string _memcachedPre;
        private readonly IMemcachedClient _memcachedClient;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mallService">Mall service.</param>
        /// <param name="memberCardService">Member card service.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="snapshot">Snapshot.</param>
        /// <param name="casaMielSession">Casa miel session.</param>
        /// <param name="paymentService">Payment service.</param>
        /// <param name="wxService">Wx service.</param>
        /// <param name="refundService">Refund service.</param>
        /// <param name="userLogService">User log service.</param>
        /// <param name="payGateWayService">Pay gate way service.</param>
        /// <param name="mediator"></param>
        /// <param name="netICService"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="optionsSnapshot"></param>
        /// <param name="order"></param>
        public MallController(IMallService mallService, IMemberCardService memberCardService, IIcApiService iicApiService, IOptionsSnapshot<MallSettings> snapshot,
                             ICasaMielSession casaMielSession, IPaymentService paymentService, IWxService wxService, IRefundService refundService,
                              IUserLogService userLogService, IPayGateWayService payGateWayService, IMediator mediator, INetICService netICService,
                              IMemcachedClient memcachedClient, IOptionsSnapshot<CasamielSettings> optionsSnapshot, IOrderService order)
        {
            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }
            if (optionsSnapshot == null) {
                throw new ArgumentNullException(nameof(optionsSnapshot));
            }
            _netICService = netICService;
            _mallService = mallService;
            _memberCardService = memberCardService;
            _icApiService = iicApiService;
            _mallSettings = snapshot.Value;
            _session = casaMielSession;
            _paymentService = paymentService;
            _wxLogin = wxService;
            _refundService = refundService;
            _userLogService = userLogService;
            _gateways = payGateWayService;
            _mediator = mediator;
            _memcachedClient = memcachedClient;
            _memcachedPre = optionsSnapshot.Value.MemcachedPre;
            _order = order;

        }

        /// <summary>
        /// 获取首页商品数据
        /// </summary>
        /// <returns>The index goods list.</returns>
        /// <remarks>
        /// {
        /// "code":0,
        ///"content": [
        /// {
        ///    "tagName": "蛋糕1",
        ///   "tagId": 1,
        ///    "tagBigImage": "蛋糕1",
        ///    "productList": []
        ///  }
        ///],
        /// "msg": "操作成功",
        ///}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<List<IndexProductBaseRsp>>> GetIndexGoodsList()
        {
            //var list = new List<Index_ProductBaseRsp>();
            //var icode = 999;
            //var message = "";

            return await _mallService.GetIndexGoodsListAsync().ConfigureAwait(false);
            //_mallService.SetIndexGoodsList(ref list, ref icode, ref message);
            //var result = new BaseResult<List<Index_ProductBaseRsp>>(list, icode, message);
            //return result;
        }


        /// <summary>
        ///  配送规则
        /// </summary>
        /// <returns></returns>
        ///<remarks>{  "code": 0, "content": { "youxuanOrderTips": "满188元包邮", "youxuanFreightMoney": 10, "youxuanOrderMoney": 188  } }
        ///</remarks>

        [HttpPost]
        [Route("[action]")]

        public async Task<IActionResult> GetFreightRule()
        {
            var rsp = await _mallService.GetFreightRule().ConfigureAwait(false);
            return Ok(new { code = 0, content = rsp });
        }
        /// <summary>
        /// 获取首页标签列表
        /// </summary>
        /// <returns>The index goods list1.</returns>
        ///<remarks>
        /// {  "code": 0,"content": [{"tagBaseId": 1,"tagName": "蛋糕1","sImgUrl": "http://img.casamiel.cn/product/181022183652804134.jpg}],"msg": ""}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<List<IndexTagBaseRsp>>> GetIndexTagsList()
        {
            //var icode = 999;
            //var message = "";
            //var list = new List<Index_TagBaseRsp>();
            return await _mallService.GetIndexTagsListAsync().ConfigureAwait(false);
            // var result = new BaseResult<List<Index_TagBaseRsp>>(list, icode, message);
            //return result;
        }
        /// <summary>
        /// 获取收获地址
        /// </summary>
        /// <param name="token">token</param>
        /// <returns>The address list.</returns>
        /// <remarks>{"code":0,"content": [ {"consigneeId": 40,  "isDefault": true,  "realName": "测",  "mobile": "18605888772",  "phone": "11860588877",  "fullAddress": "杭州玫隆食品有限公司(杭州市江干区) 三号大街201号", "provinceId": 0,"cityId": 0,  "districtId": 0, "postcode": ""}],"msg":"" }
        ///</remarks>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<List<AddressBaseRsp>>> GetAddressList([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            return await _mallService.GetAddressListAsync(mobile).ConfigureAwait(false);
        }

        /// <summary>
        /// 保存收货地址
        /// </summary>
        /// <returns>The address save.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        /// <remarks>{"code":0,"msg"=""}</remarks>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<string>> AddressSave(AddressSaveBaseReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);
            var data = new {
                req.IsDefault,
                req.ConsigneeId,
                req.ProvinceId,
                req.CityId,
                req.LinkName,
                req.DistrictId,
                req.Phone,
                req.FullAddress,
                req.Postcode,
                Mobile = mobile
            };


            return await _mallService.SaveAddressAsync(JsonConvert.SerializeObject(data)).ConfigureAwait(false);//, ref icode, ref message);
            //var result = new BaseResult<string>("", icode, message);
            //return result;
        }

        /// <summary>
        /// 通过名称模糊查找到商品
        /// </summary>
        /// <returns>The product list by search.</returns>
        /// <param name="data">Data.</param>
        [HttpPost]
        [Route("[Action]")]
        public async Task<PagingResultRsp<List<ProductBaseRsp>>> GetProductListBySearch([FromBody]GetProductListBySearchReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var cmd = new ProductGetListBySearchNameCommand { PageIndex = data.PageIndex, PageSize = data.PageSize, Name = data.Name, Platfrom = 1 };
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// Gets the address base.
        /// </summary>
        /// <returns>The address base.</returns>
        /// <remarks>{"code":0,content:  {"consigneeId": 49,"isDefault": true,"realName": "1",|"mobile": "18605888772", "phone": "18605888772","fullAddress": "1111","provinceId": 0,"cityId": 0, "districtId": 0,"postcode": ""  }
        ///</remarks>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<AddressBaseRsp>> GetAddressBase(GetAddressBaseReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);
            return await _mallService.GetAddressBaseAsync(mobile, req.consigneeId).ConfigureAwait(false);// ref rep, ref icode, ref message);
        }

        /// <summary>
        /// 设置默认地址
        /// </summary>
        /// <returns>The address default.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<string>> SetAddressDefault(GetAddressBaseReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            var mobile = MemberHelper.GetMobile(token);
            //var icode = 999;
            //var message = "";
            return await _mallService.SetAddressDefaultAsync(mobile, req.consigneeId).ConfigureAwait(false);//, ref icode, ref message);
            //var result = new BaseResult<string>("", icode, message);
            //return result;
        }
        /// <summary>
        /// 删除地址
        /// </summary>
        /// <returns>The delete.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<string>> AddressDelete([FromBody] GetAddressBaseReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);
            //var icode = 999;
            //var message = "";
            var rsp = await _mallService.AddressDeleteAsync(mobile, req.consigneeId).ConfigureAwait(false);//, ref icode, ref message);
            return rsp;
            //var result = new BaseResult<string>("", icode, message);
            //return result;
        }

        /// <summary>
        /// 获取分类下产品列表
        /// </summary>
        /// <returns>The goods list.</returns>
        /// <param name="req">Req.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<PagingResultRsp<List<ProductBaseRsp>>> GetGoodsList([FromBody] GoodsGetListReq req)
        {
            //var list = new List<ProductBaseRsp>();
            //var icode = 999;
            //var message = "";
            //var total = 0;
            return await _mallService.GetGoodsListAsync(req).ConfigureAwait(false);
            //var result = new PagingResults<List<ProductBaseRsp>>(list, req.PageIndex, req.PageSize, total, icode, message);
            //return result;
        }


        /// <summary>
        /// 通过产品ProductBaseId 获取商品明细
        /// </summary>
        /// <returns>The good detail.</returns>
        /// <param name="req">Req.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<GoodsBaseRsp>> GetGoodDetail([FromBody] GetGoodDetailReq req)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            return await _mallService.GetGoodsDetailAsync(req.id).ConfigureAwait(false);
        }


        /// <summary>
        /// 添加到购物车
        /// </summary>
        /// <returns>The shopping cart.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<string>> AddShoppingCart(AddShoppingCartReq req, [FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            //var mobile = "18605888772";
            //var icode = 999;
            //var message = "";
            return await _mallService.AddShoppingCartAsync(req, mobile).ConfigureAwait(false);
            // return new BaseResult<string>("", icode, message);
        }

        /// <summary>
        /// 修改购物车商品数量
        /// </summary>
        /// <returns>The cart change quantity.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<string>> ShoppingCartChangeQuantity(AddShoppingCartReq req, [FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            //var icode = 999;
            //var message = "";
            return await _mallService.ShoppingCartChangeQuantityAsync(req, mobile).ConfigureAwait(false);
            // return new BaseResult<string>("", icode, message);
        }
        /// <summary>
        /// 设置选中和不选中
        /// </summary>
        /// <returns>The cart set check.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<string>> ShoppingCartSetCheck(ShoppingCartSetIsCheckReq req, [FromHeader(Name = "u-token")]
                                                  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);
            var rsp = await _mallService.ShoppingCartSetCheckAsync(req).ConfigureAwait(false);
            return rsp;
        }
        /// <summary>
        /// 删除购物车商品
        /// </summary>
        /// <returns>The cart delete.</returns>
        /// <param name="req">Identifiers.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<string>> ShoppingCartDelete(CartDeleteReq req, [FromHeader(Name = "u-token")]  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);

            var rsp = await _mallService.ShoppingCartDeleteAsync(req.Ids, mobile).ConfigureAwait(false);
            return rsp;
        }
        /// <summary>
        /// 获取购物车商品集合
        /// </summary>
        /// <returns>The shopping cart list.</returns>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<List<Application.Models.Mall.Rsp.ShoppingCartBaseRsp>>> GetShoppingCartList([FromHeader(Name = "u-token")]  string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            //var icode = 999;
            //var message = "";
            //var list = new List<Application.Models.Mall.Rsp.ShoppingCartBaseRsp>();
            return await _mallService.GetShoppingCartListAsync(mobile).ConfigureAwait(false);
            // return new BaseResult<List<Application.Models.Mall.Rsp.ShoppingCartBaseRsp>>(list, icode, message);
        }

        /// <summary>
        /// 下单
        /// </summary>
        /// <returns>The order.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<PaymentRsp>>> CreateOrder(OrderCreateReq req, [FromHeader(Name = "u-token")]  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            logger.Trace($"CreateOrder:{JsonConvert.SerializeObject(req)}");
            var mobile = MemberHelper.GetMobile(token);
            var cardlist = await _memberCardService.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            var _cardno = "";

            if (cardlist != null && cardlist.Count(c => c.IsBind == true) == 2) {
                var vipcard = cardlist.SingleOrDefault(c => c.IsBind == true && c.CardType != "3");
                if (vipcard != null) {
                    _cardno = vipcard.CardNO;
                }
            }

            if (req.GoodsList == null || !req.GoodsList.Any()) {
                return new BaseResult<PaymentRsp>(null, 9999, "请选中产品");
            }
            IcPriceReq dto = new IcPriceReq { Shopid = _mallSettings.ShopId, Product = new List<ProductItemReq>() };

            foreach (var item in req.GoodsList) {
                dto.Product.Add(new ProductItemReq { Pid = $"{item.GoodsRelationId}", Count = item.GoodsQuantity });
            }


            //var zmodle = _icApiService.productstockquery(dto).GetAwaiter().GetResult();
            //if (zmodle != null && zmodle.product.Count > 0)
            //{
            //    foreach (var item in req.GoodsList)
            //    {
            //        var p = zmodle.product.Find(c => c.pid == item.GoodsRelationId.ToString());
            //        if (p == null)
            //        {
            //            // return BaseResult < PaymentRsp >
            //            // return Ok(new { code = -22, msg = $"{item.GoodsRelationId.ToString()}产品已经下架" });
            //            return new BaseResult<PaymentRsp>(null, -22, $"{item.GoodsRelationId.ToString()}产品已经下架");
            //        }
            //        item.Price = p.icprice;
            //    }
            //}
            //else
            //{
            //    return new BaseResult<PaymentRsp>(null, -22, "产品已经下架");
            //    //return Ok(new { code = -22, msg = "产品已经下架" });
            //}
            if (req.DiscountCouponId > 0) {
                var ticketreq = new GetTicticketReq { Cardno = req.CardNo, Pagesize = 200, State = 2, Pageindex = 1 };
                logger.Trace($"GeticticketReq:{JsonConvert.SerializeObject(ticketreq)}");
                var a = await _icApiService.Geticticket(ticketreq).ConfigureAwait(false);
                if (a.code == 0) {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    var ticket = list.Tickets.Where(t => t.Ticketid == req.DiscountCouponId).SingleOrDefault();
                    if (ticket != null) {
                        req.DiscountCouponMoney = ticket.Je.ToDecimal(0);
                        req.DiscountCouponName = ticket.Ticketname;
                    } else {
                        return new BaseResult<PaymentRsp>(null, -23, "优惠券不可用");
                    }
                } else {
                    return new BaseResult<PaymentRsp>(null, -23, "优惠券不可用");
                }
            }

            if (string.IsNullOrEmpty(req.Paycardno)) {
                foreach (var item in cardlist) {
                    if (item.IsBind) {
                        _cardno = item.CardNO;
                        break;
                    }
                }
            } else {
                _cardno = req.Paycardno;
            }

            if (req.payMethod == 3) {
                if (string.IsNullOrEmpty(req.Paycardno)) {
                    return Ok(new { code = 999, msg = "卡号不能为空" });
                }
                var zcard = await _icApiService.GetCardBalance(req.Paycardno,$"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                if (zcard.code == 0) {
                    var payMoney = 0m;
                    payMoney = req.GoodsList.Sum(x => x.Price * x.GoodsQuantity);

                    var cardinfo = JsonConvert.DeserializeObject<JObject>(zcard.content);
                    var balance = cardinfo["totalmoney"].ToDecimal(0);
                    if ((balance - req.DiscountCouponMoney) + req.FreightMoney < payMoney) {
                        return Ok(new { code = -39, msg = "卡内余额不足" });
                    }
                } else {
                    return Ok(zcard);
                }
            }
            var ictradeNO = "";
            var billNO = "";
            var icdto = new IcconsumeReq { Phoneno = mobile, Cardno = _cardno, Shopid = _mallSettings.ShopId, Pickuptime = DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture) };
            icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>();
            foreach (var item in req.GoodsList) {
                icdto.Product.Add(new IcconsumeReq.IcconsumeProductItem { Pid = $"{item.GoodsRelationId}", Count = item.GoodsQuantity });

            }
            var icentity = await _icApiService.Icconsume(icdto).ConfigureAwait(false);

            if (icentity.code == 0) {
                var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
                ictradeNO = jobject["tradeno"].ToString();
                billNO = jobject["billno"].ToString();
            } else {
                return new BaseResult<PaymentRsp>(null, icentity.code, icentity.msg);
                //  return Ok(icentity);
            }
            req.IcTradeNO = ictradeNO;
            req.Mobile = mobile;
            req.BillNo = billNO;
            try {

                var data = await _mallService.CreateOrder(req).ConfigureAwait(false);
                if (data.Code != 0) {
                    var backDto = new IcConsumeBackReq { Phoneno = mobile, Cardno = _cardno, Tradeno = ictradeNO };

                    var d = await _icApiService.Icconsumeback(backDto).ConfigureAwait(false);
                    logger.Error($"{JsonConvert.SerializeObject(backDto)},{JsonConvert.SerializeObject(d)}");
                    //return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
                    return new BaseResult<PaymentRsp>(null, data.Code, data.Msg);
                }

                var entity = new MWebOrderBaseRsp();
                var orderbase = await _mallService.GetOrderBase(mobile, data.Content.OrderCode).ConfigureAwait(false);
                if (orderbase.Code == 0) {
                    entity = orderbase.Content;
                } else {
                    return new BaseResult<PaymentRsp>(null, data.Code, data.Msg);
                }
                var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CurrentCulture)}";

                var payment = new PaymentRecord { OperationMethod = 4, TradeNo = p_tradeno, Amount = entity.PayMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0), PayMethod = 3, BillNO = entity.OrderCode, IcTradeNO = entity.IcTradeNO, State = 0, OperationState = 0, CreateTime = DateTime.Now, Mobile = mobile };
                var shopinfo = await _paymentService.GetShopIdAndShopNameByBillNOAsync<ICasaMielSession>(entity.OrderCode).ConfigureAwait(false);
                payment.ShopName = shopinfo.Item2;
                payment.ShopId = shopinfo.Item1;
                var shopno = "";
                if (payment.ShopId.HasValue) {
                    var basedata = await _icApiService.BasedataQuery(new BasedataqueryReq { Datatype = 3, Datavalue = $"{payment.ShopId.Value}" }).ConfigureAwait(false);
                    if (basedata.code == 0) {
                        var d = JsonConvert.DeserializeObject<JArray>(basedata.content);
                        if (d.Count > 0) {
                            shopno = d[0]["no"].ToString();
                        }
                    }
                }
                switch (req.payMethod) {
                    case 3://会员卡


                        //if (string.IsNullOrEmpty(req.Paycardno))
                        //{
                        //    return Ok(new { code = 999, msg = "卡号不能为空" });
                        //}
                        //var zcard = await _icApiService.GetCardBalance(req.Paycardno);
                        //if (zcard.code == 0)
                        //{
                        //    var cardinfo = JsonConvert.DeserializeObject<JObject>(zcard.content);
                        //    var balance = cardinfo["totalmoney"].ToDecimal(0);
                        //    if ((balance + req.DiscountCouponMoney) < entity.PayMoney)
                        //    {
                        //        return Ok(new { code = -39, msg = "卡内余额不足" });
                        //    }
                        //}
                        //else
                        //{
                        //    return Ok(zcard);
                        //}

                        var pay = new IcConsumepayReq {
                            Phoneno = mobile,
                            Cardno = req.Paycardno,
                            Shopid = _mallSettings.ShopId,
                            Tradeno = ictradeNO,
                            Createinvoice = true
                        };
                        pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                        {
                            new IcConsumepayReq.PaycontentItem
                            {
                                Paytype = "3",
                                Paymoney = entity.PayMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                                Paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}"
                            }
                        };
                        if (req.DiscountCouponId > 0) {
                            pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                                Paytype = "6",
                                Paymoney = req.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                                Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                                Payuser = $"{req.DiscountCouponId}"
                            });
                        }

                        if (req.FreightMoney > 0) {
                            pay.Payfee = new List<IcConsumepayReq.PayfeeItem>{new IcConsumepayReq.PayfeeItem
                        {
                            Fee = req.FreightMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Feetype="1",
                             Description = "配送费"
                        }};
                        }

                        var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                        logger.Trace($"mallorderpay;req:{JsonConvert.SerializeObject(pay)},result:{JsonConvert.SerializeObject(zmodel)}");
                        if (zmodel.code == 0) {
                            var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                            if (jobject != null && jobject["invoiceqrcode"] != null) {
                                var invoiceUrl = jobject["invoiceqrcode"].ToString();
                                await _order.UpdateOrderInvoiceUrlByOrderCodeAsync<ICasaMielSession>(payment.BillNO, invoiceUrl).ConfigureAwait(false);
                            } else {
                                this.logger.Error($"Invoideurl:{zmodel.content}");
                            }
                            var p = new PaymentRsp { Payed = true, PayMethod = 3, Paymentrequest = "", OrderCode = entity.OrderCode };
                            //await _storeService.AddNoticeAsync(noticEntity, uow);
                            var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"订单支付,卡号:[{req.Paycardno},支付金额{entity.PayMoney}，订单号：{entity.OrderCode}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                            await _userLogService.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                            await _mallService.OrderChangeStatus(entity.OrderCode, mobile, 1, 3, "").ConfigureAwait(false);

                            var orderen = await _order.GetByOrderCodeAsync<ICasaMielSession>(entity.OrderCode).ConfigureAwait(false);
                            payment.PayMethod = 3;
                            payment.State = 1;
                            payment.PayTime = DateTime.Now;
                            using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                                orderen.OrderStatus = (int)OrderStatus.Paid;
                                orderen.PayTime = DateTime.Now;
                                await _order.OrderBaseUPdateAsync(orderen, uow).ConfigureAwait(true);
                                await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);
                            }
                            return new BaseResult<PaymentRsp>(p, 0, "");
                        } else {
                            return new BaseResult<PaymentRsp>(null, zmodel.code, zmodel.msg);
                        }

                    case 1://微信支付

                        payment.PayMethod = 1;
                        payment.Remark = "app微信支付";
                        //await _paymentService.AddAsync<ICasaMielSession>(payment);
                        break;
                    //var paymentrequst = _gateways.CreateWechatpayOrder(p_tradeno, payment.Amount,payment.ShopName,shopno);
                    // var jsonrs = new { code = 0, content = new { paymentrequest = paymentrequst, ordercode = entity.OrderCode, payMethod = "1", payed = false } };
                    // return Ok(jsonrs);
                    // return new BaseResult<PaymentRsp>(new PaymentRsp { OrderCode = entity.OrderCode, Paymentrequest = paymentrequst, Payed = false, PayMethod = payment.PayMethod }, 0, "");
                    //return new JsonResult(new { code = 0, content = paymentrequst, payMethod = 1 });
                    case 2://支付宝
                        payment.PayMethod = 2;
                        payment.Remark = "app支付宝支付";
                        break;
                    //await _paymentService.AddAsync<ICasaMielSession>(payment);
                    //var paymentrequsta = _gateways.CreateAlipayOrder(p_tradeno, payment.Amount,payment.ShopName,shopno);
                    // var jsonr = new { code = 0, content = new { paymentrequest = paymentrequsta, ordercode = order.OrderCode, payMethod = "2", payed = false } };
                    //  return new BaseResult<PaymentRsp>(new PaymentRsp { Payed = false, PayMethod = 2, Paymentrequest = paymentrequsta, OrderCode = entity.OrderCode }, 0, "");
                    //return new JsonResult(new { code = 0, content = paymentrequsta, payMethod = 2, payed = false });
                    case 4://小程序
                        if (req.id < 0) {
                            // return OK(new { code = -13, msg = "openid不存在" });
                            return new BaseResult<PaymentRsp>(null, -13, "openid不存在");
                        }
                        var wxloginentity = await _wxLogin.GetByIdAsync<ICasaMielSession>(req.id).ConfigureAwait(false);
                        if (wxloginentity == null) {
                            return new BaseResult<PaymentRsp>(null, -13, "openid不存在");
                        }
                        payment.PayMethod = 4;
                        payment.Remark = "小程序微信支付";
                        break;
                        //await _paymentService.AddAsync<ICasaMielSession>(payment);
                        //logger.Trace(JsonConvert.SerializeObject(wxloginentity));

                        //var paymentrequstm = _gateways.CreateMiniWechatpayOrder(p_tradeno, payment.Amount, wxloginentity.openId, wxloginentity.appId, payment.ShopName, shopno, DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
                        //logger.Trace(paymentrequstm);
                        //var json = new { code = 0, content = new { paymentrequest = paymentrequstm, ordercode = order.OrderCode, payMethod = "4", payed = false } };
                        // return new BaseResult<PaymentRsp>(new PaymentRsp { Payed = false, PayMethod = 4, Paymentrequest = paymentrequstm, OrderCode = entity.OrderCode }, 0, "");


                }
                var cmd = new CreatePaymentRequestCommand(payment, req.id, PaymentScenario.Mall);
                var result = await _mediator.Send(cmd).ConfigureAwait(false);
                return new BaseResult<PaymentRsp>(new PaymentRsp { Payed = result.Payed, PayMethod = result.PayMethod.ToInt32(0), Paymentrequest = result.Paymentrequest, OrderCode = result.Ordercode }, 0, "");

            } catch (System.Net.WebException ex) {
                var backDto = new IcConsumeBackReq { Phoneno = mobile, Cardno = _cardno, Tradeno = ictradeNO };
                var d = await _icApiService.Icconsumeback(backDto).ConfigureAwait(false);
                logger.Error($"{JsonConvert.SerializeObject(req)},{JsonConvert.SerializeObject(d)}");
                logger.Error(ex.StackTrace);
                throw new CasamielDomainException("mallorder", ex);

            }

        }
        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <returns>The order base.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<MWebOrderBaseRsp>>> GetOrderBase(GetOrderBaseReq req, [FromHeader(Name = "u-token")]  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);
            var result = await _mallService.GetOrderBase(mobile, req.ordercode).ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <returns>The order list.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<PagingResultRsp<List<MWebOrderListRsp>>>> GetOrderList(MWebOrderGetListReq req, [FromHeader(Name = "u-token")]  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);
            var result = await _mallService.GetOrderList(req.Status, mobile, req.PageIndex, req.PageSize).ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// 订单到货确认
        /// </summary>
        /// <returns>The arrival confirm.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<string>>> OrderArrivalConfirm(GetOrderBaseReq req, [FromHeader(Name = "u-token")]  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            var mobile = MemberHelper.GetMobile(token);
            var result = await _mallService.OrderChangeStatus(req.ordercode, mobile, 2, 0, "").ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns>The order.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<string>>> CancelOrder(CancelOrderReq req, [FromHeader(Name = "u-token")]  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var mobile = MemberHelper.GetMobile(token);
            logger.Trace($"{JsonConvert.SerializeObject(req)}");

            var result = await _mallService.GetOrderBase(mobile, req.OrderCode).ConfigureAwait(false);
            logger.Trace($"CancelOrder:{JsonConvert.SerializeObject(result)}");
            if (result.Code == 0) {
                var order = result.Content;
                if (order.OrderStatus == 2) {

                    if (order.ExpressStatus > 1) {
                        return Ok(new { code = 9999, msg = "已发货不能取消订单" });
                    }
                    var m = await _refundService.OrderRefund(new OrderRefundReq { OrderCode = order.OrderCode }).ConfigureAwait(false);
                    if (m.code == 0) {
                        var r = await _mallService.GetOrderBase(req.OrderCode, mobile).ConfigureAwait(false);
                        if (r.Code == 0) {
                            var d = await _mallService.OrderChangeStatus(req.OrderCode, mobile, 3, order.PayMethod, r.Content.ResBillNo).ConfigureAwait(false);
                            return d;
                        }

                    }
                    return Ok(m);
                } else {
                    return Ok(new { code = 9999, msg = "订单状态不是已支付" });
                }
            } else {
                return Ok(new { code = 9999, msg = "订单不存在！" });
            }
        }

        /// <summary>
        /// 获取展位数据
        /// </summary>
        /// <returns>The boot list.</returns>
        /// <param name="req">Req.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<ActionResult<BaseResult<List<MWeb_Booth_GetListRsp>>>> GetBootList([FromBody]GetBoothListReq req)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            return await _mallService.GetBoothList(req.Code).ConfigureAwait(false);
        }
        /// <summary>
        /// Gets the new by identifier.
        /// </summary>
        /// <returns>The new by identifier.</returns>
        /// <param name="req">Req.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<MWebNewsBaseRsp>> GetNewById([FromBody]MWebIdReq req)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            return await _mallService.GetNewById(req.Id).ConfigureAwait(false);
        }








        /// <summary>
        ///我的会员券
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<List<TicketItem>>> GetMyTickets(GetTicketRequest request, [FromHeader(Name = "u-token")] string token)
        {
            if (request is null) {
                throw new ArgumentNullException(nameof(request));
            }

            var mobile = MemberHelper.GetMobile(token);
            var glist = new List<Domain.Request.Waimai.TakeOutOrderGoods>();
            foreach (var item in request.GoodsList) {
                glist.Add(new Domain.Request.Waimai.TakeOutOrderGoods {
                    GoodsBaseId = item.GoodsBaseId,
                    GoodsQuantity = item.GoodsQuantity,
                    GoodsRelationId = item.GoodsRelationId,
                    Price = item.Price

                });
            }

            var cmd = new GetTicketsStatusByOrderCommand(glist, _mallSettings.StoreId, mobile,false,LoginInfo.Item3);
            return await _mediator.Send(cmd).ConfigureAwait(false);

        }





        /// <summary>
        /// 我的优惠券
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<List<TicketItem>>>> GetMyCoupon([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);

            var cardinfo = await _memberCardService.GetBindCardAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (cardinfo != null) {
                var t = new GetTicticketReq { Cardno = cardinfo.CardNO, State = 2, Pageindex = 1, Pagesize = int.MaxValue };
                var a = await _icApiService.Geticticket(t).ConfigureAwait(false);
                if (a.code == 0) {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    return new BaseResult<List<TicketItem>>(list.Tickets, 0, "");
                }
            }
            var ticket = new List<TicketItem>();
            return new BaseResult<List<TicketItem>>(ticket, 0, "");

        }

        /// <summary>
        /// Payment the specified data and token.
        /// </summary>
        /// <returns>The payment.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<PaymentRsp>> Payment([FromBody] OrderPaymentReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var mobile = MemberHelper.GetMobile(token);
            var order = new MWebOrderBaseRsp();
            var orderResult = await _mallService.GetOrderBase(mobile, data.OrderCode).ConfigureAwait(false);
            if (orderResult.Code != 0) {
                // return Ok(new { code = -23, msg = "订单不存在" });
                return new BaseResult<PaymentRsp>(null, -23, "订单不存在");
            }
            order = orderResult.Content;
            if (order.OrderStatus != 1) {
                //return Ok(new { code = -24, msg = "订单状态不是待支付" });
                return new BaseResult<PaymentRsp>(null, -24, "订单状态不是待支付");
            }

            if (data.DiscountCouponId > 0) {
                var a = await _icApiService.Geticticket(new GetTicticketReq { Cardno = data.CardNO, Pagesize = 200, State = 2, Pageindex = 1 }).ConfigureAwait(false);
                if (a.code == 0) {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    var ticket = list.Tickets.SingleOrDefault(t => t.Ticketid == data.DiscountCouponId);
                    if (ticket != null) {
                        data.DiscountCouponMoney = ticket.Je.ToDecimal(0);
                    } else {
                        return new BaseResult<PaymentRsp>(null, -23, "优惠券不可用");
                        // return Ok(new { code = -23, msg = "优惠券不可用" });
                    }
                } else {
                    return new BaseResult<PaymentRsp>(null, -23, "优惠券不可用");
                    // return Ok(new { code = -23, msg = "优惠券不可用" });
                }
            }
            var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CurrentCulture)}";
            //var reorder = await _storeApiService.GetOrderByOrderCodeAsync(data.OrderCode, mobile);
            // var entity = await _storeService.GetByOrderCodeAsync<ICasaMielSession>(order.OrderCode, mobile);
            var payment = new PaymentRecord { OperationMethod = 4, TradeNo = p_tradeno, Amount = order.PayMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0), PayMethod = 3, BillNO = order.OrderCode, IcTradeNO = order.IcTradeNO, State = 0, OperationState = 0, CreateTime = DateTime.Now, Mobile = mobile };
            if (order.PayMoney == 0) {
                var pay = new IcConsumepayReq {
                    Shopid = _mallSettings.ShopId,
                    Tradeno = order.IcTradeNO,
                    Phoneno = mobile,
                    Createinvoice = true
                };
                pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>();

                if (data.DiscountCouponId > 0) {
                    pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                        Paytype = "6",
                        Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                        Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                        Payuser = $"{data.DiscountCouponId}"
                    });
                }
                var orderen = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.OrderCode).ConfigureAwait(false);
                var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                if (zmodel.code == 0) {
                    var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                    if (jobject != null && jobject["invoiceqrcode"] != null) {
                        var invoiceUrl = jobject["invoiceqrcode"].ToString();
                        await _order.UpdateOrderInvoiceUrlByOrderCodeAsync<ICasaMielSession>(payment.BillNO, invoiceUrl).ConfigureAwait(false);
                    } else {
                        this.logger.Error($"Invoideurl:{zmodel.content}");
                    }

                    payment.PayMethod = data.PayMethod;
                    payment.PayTime = DateTime.Now;
                    payment.State = 1;
                    payment.OperationState = 1;
                    using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                        orderen.Status = 2;
                        orderen.PayTime = DateTime.Now;
                        await _order.OrderBaseUPdateAsync(orderen, uow).ConfigureAwait(true);
                        //order.OrderStatus = 2;
                        //order.PayTime = DateTime.Now;
                        //await _storeService.OrderBaseUPdateAsync(order, uow);
                        //await _storeService.UpdateOrderTakeStatus(order.OrderBaseId, 0, "", uow);
                        //payment.State = 1;
                        //payment.OperationState = 1;
                        //payment.PayTime = DateTime.Now;
                        await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);
                        //var noticEntity = new Notice_baseEntity()
                        //{
                        //    RemindTime = DateTime.Now.AddMinutes(-3),
                        //    CreateTime = DateTime.Now,
                        //    RelationId = order.OrderBaseId,
                        //    StoreId = order.StoreId,
                        //    NoticeType = 0
                        //};
                        //await _storeService.AddNoticeAsync(noticEntity, uow);

                    }
                    await _mallService.OrderChangeStatus(order.OrderCode, mobile, 1, 3, "").ConfigureAwait(false);
                    var payed = new PaymentRsp { PayMethod = payment.PayMethod, Paymentrequest = "", OrderCode = order.OrderCode, Payed = true };
                    return new BaseResult<PaymentRsp>(payed, 0, "");
                    //return new JsonResult(new { code = 0, content = new { paymentrequest = "", ordercode = order.OrderCode, payMethod = payment.PayMethod.ToString(), payed = true } });

                    //return new JsonResult(new { code = 0, content = entity, payMethod = payment.PayMethod, payed = true });
                }
                return new BaseResult<PaymentRsp>(null, zmodel.code, zmodel.msg);
            }

            var shopno = "";
            var shopinfo = await _paymentService.GetShopIdAndShopNameByBillNOAsync<ICasaMielSession>(order.OrderCode).ConfigureAwait(false);
            payment.ShopName = shopinfo.Item2;
            payment.ShopId = shopinfo.Item1;
            if (payment.ShopId.HasValue) {
                var cachekey = string.Format(CultureInfo.CurrentCulture, Constant.SHOPNO, _memcachedPre, payment.ShopId.Value);
                shopno = await _memcachedClient.GetValueAsync<string>(cachekey).ConfigureAwait(false);
                if (string.IsNullOrEmpty(shopno)) {
                    var basedata = await _icApiService.BasedataQuery(new BasedataqueryReq { Datatype = 3, Datavalue = $"{payment.ShopId.Value}" }).ConfigureAwait(false);
                    if (basedata.code == 0) {
                        var d = JsonConvert.DeserializeObject<JArray>(basedata.content);
                        if (d.Count > 0) {
                            shopno = d[0]["no"].ToString();
                            await _memcachedClient.AddAsync(cachekey, shopno, 72000).ConfigureAwait(false);
                        }
                    }
                }
            }
            payment.ShopNO = shopno;
            switch (data.PayMethod) {
                case 3:
                    if (string.IsNullOrEmpty(data.PayCardNO)) {
                        return new BaseResult<PaymentRsp>(null, 999, "卡号不能为空");
                        //return Ok(new { code = 999, msg = "卡号不能为空" });
                    }
                    var pay = new IcConsumepayReq {
                        Cardno = data.PayCardNO,
                        Shopid = _mallSettings.ShopId,
                        Tradeno = order.IcTradeNO
                    };
                    pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                    {
                        new IcConsumepayReq.PaycontentItem
                        {
                            Paytype = "3",
                            Paymoney = order.PayMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}"
                        }
                    };
                    if (data.DiscountCouponId > 0) {
                        pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                            Paytype = "6",
                            Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                            Payuser = $"{data.DiscountCouponId}"
                        });
                    }
                    if (order.FreightMoney > 0) {
                        pay.Payfee = new List<IcConsumepayReq.PayfeeItem>{new IcConsumepayReq.PayfeeItem
                        {
                            Fee = order.FreightMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Feetype="1",
                            Description = "配送费"
                        }};
                    }
                    payment.PayMethod = 3;
                    payment.State = 1;
                    payment.OperationState = 1;
                    payment.PayTime = DateTime.Now;
                    var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                    logger.Trace($"mallorderpay;req:{pay},result:{zmodel}");
                    if (zmodel.code == 0) {
                        //var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                        //var tradeno = jobject["tradeno"].ToString();
                        //payment.OutTradeNo = tradeno;
                        //todo:zhifucg
                        using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                            order.OrderStatus = 2;
                            //await _storeService.OrderBaseUPdateAsync(order, uow);
                            //await _storeService.UpdateOrderTakeStatus(order.OrderBaseId, 0, "", uow);
                            await _paymentService.AddAsync(payment, uow).ConfigureAwait(false);

                        }
                        await _mallService.OrderChangeStatus(order.OrderCode, mobile, 1, 3, "").ConfigureAwait(false);
                        var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"蛋糕订单支付,卡号:[{data.CardNO},支付金额{order.PayMoney}，订单号：{order.OrderCode}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                        await _userLogService.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                        // return new JsonResult(new { code = 0, content = new { paymentrequest = "", ordercode = order.OrderCode, payMethod = payment.PayMethod.ToString(), payed = true } });
                        var paycard = new PaymentRsp { PayMethod = payment.PayMethod, Paymentrequest = "", OrderCode = order.OrderCode, Payed = true };
                        return new BaseResult<PaymentRsp>(paycard, 0, "");

                        //return new JsonResult(new { code = 0, content = entity, payMethod = 3, payed = true });
                    } else {
                        return new BaseResult<PaymentRsp>(null, zmodel.code, zmodel.msg);
                    }

                case 1:
                    payment.PayMethod = 1;
                    payment.Remark = "app微信支付";
                    await _paymentService.AddAsync<ICasaMielSession>(payment).ConfigureAwait(false);
                    var paymentrequst = _gateways.CreateWechatpayOrder(p_tradeno, payment.Amount, payment.ShopName, shopno);
                    //return new JsonResult(new { code = 0, content = paymentrequst, payMethod = 1, payed = false });
                    //return new JsonResult(new { code = 0, content = new { paymentrequest = paymentrequst, ordercode = order.OrderCode, payMethod = payment.PayMethod.ToString(), payed = false } });
                    var payed = new PaymentRsp { PayMethod = payment.PayMethod, Paymentrequest = paymentrequst, OrderCode = order.OrderCode, Payed = false };
                    return new BaseResult<PaymentRsp>(payed, 0, "");

                case 2:
                    payment.PayMethod = 2;
                    payment.Remark = "app支付宝支付";
                    await _paymentService.AddAsync<ICasaMielSession>(payment).ConfigureAwait(false);
                    var paymentrequsta = _gateways.CreateAlipayOrder(p_tradeno, payment.Amount, payment.ShopName, shopno);
                    var payedzfb = new PaymentRsp { PayMethod = payment.PayMethod, Paymentrequest = paymentrequsta, OrderCode = order.OrderCode, Payed = false };
                    return new BaseResult<PaymentRsp>(payedzfb, 0, "");
                //return new JsonResult(new { code = 0, content = new { paymentrequest = paymentrequsta, ordercode = order.OrderCode, payMethod = payment.PayMethod.ToString(), payed = false } });
                //return new JsonResult(new { code = 0, content = paymentrequsta, payMethod = 2, payed = false });
                case 4:
                    if (data.id < 0) {
                        return new BaseResult<PaymentRsp>(null, -13, "openid不存在");
                        // return new JsonResult(new { code = -13, msg = "openid不存在" });
                    }
                    var wxloginentity = await _wxLogin.GetByIdAsync<ICasaMielSession>(data.id).ConfigureAwait(false);
                    if (wxloginentity == null) {
                        return new BaseResult<PaymentRsp>(null, -13, "openid不存在");
                        // return new JsonResult(new { code = -13, msg = "openid不存在" });
                    }

                    payment.PayMethod = 4;
                    payment.Remark = "小程序微信支付";
                    await _paymentService.AddAsync<ICasaMielSession>(payment).ConfigureAwait(false);
                    logger.Trace($"{JsonConvert.SerializeObject(payment)}");
                    var paymentrequstm = _gateways.CreateMiniWechatpayOrder(p_tradeno, payment.Amount, wxloginentity.OpenId, wxloginentity.AppId, payment.ShopName, payment.ShopNO, DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss", CultureInfo.CurrentCulture));
                    logger.Trace($"小程序微信支付" + paymentrequstm);
                    //return new JsonResult(new { code = 0, content = paymentrequstm, payMethod = 4, payed = false });
                    //  return new JsonResult(new { code = 0, content = new { paymentrequest = paymentrequstm, ordercode = order.OrderCode, payMethod = payment.PayMethod.ToString(), payed = false } });
                    var payedwx = new PaymentRsp { PayMethod = payment.PayMethod, Paymentrequest = paymentrequstm, OrderCode = order.OrderCode, Payed = false };
                    return new BaseResult<PaymentRsp>(payedwx, 0, "");
            }
            return new BaseResult<PaymentRsp>(null, 999, "出错了");
        }

    }
}
